<?php

namespace App\X;


use App\Common\Log;
use App\Common\SysContext;
use XWX\Common\H;

class EHelper
{
    /**
     * 是否 dev
     *
     * @return bool
     */
    static function funcIsDev()
    {
        return \EasySwoole\EasySwoole\Core::getInstance()->isDev();
    }

    /**
     * 获取配置文件
     *
     * @param null|string $key
     * @return array|mixed|null
     */
    static function funcGetConf(?string $key)
    {
        return \EasySwoole\EasySwoole\Config::getInstance()->getConf($key);
    }


    /**
     * 获取唯一ID
     *
     * @param string $prefix
     * @return string
     */
    static function funcGetID($prefix = '')
    {
        return uniqid(str_replace('_', '-', $prefix)) . self::funcGetOrderID();
    }


    /**
     * 获取唯一订单ID
     *
     * @param int $sys_num
     * @return int
     */
    static function funcGetOrderID($sys_num = 1)
    {
        $worder_id = 0;
        if (!H::funcIsWin())
        {
            $worder_id = \EasySwoole\EasySwoole\ServerManager::getInstance()->getSwooleServer()->worker_id;
        }

        return \EasySwoole\Utility\SnowFlake::make($sys_num, $worder_id) . '';
    }


    /**
     * 开启协程-协程结束会释放上下文
     * @param $go_func
     * @param null $defer_func
     */
    static function funcGo($go_func, $defer_func = null)
    {
        go(function () use ($go_func, $defer_func)
        {
            $co_id = SysContext::funcInsStatic()->getCoroutineID();

            Log::funcLogInfo(__METHOD__, "开启-子协程[{$co_id}]");

            if (is_callable($go_func))
            {
                $go_func();
            }

            defer(function () use ($defer_func, $co_id)
            {
                Log::funcLogInfo(__METHOD__, "结束-子协程[{$co_id}]-释放上下文资源");
                SysContext::funcInsStatic()->destroy();

                if (is_callable($defer_func))
                {
                    $defer_func();
                }
            });
        });
    }
}